package progress

import (
	"fmt"
	"sync/atomic"
)

type Progress struct {
	all                  int64
	lastPercent          float64
	currentSegmentFactor float64
	//currentSegmentPercent float64
	piecePercent []int32 //每片的进度
	rsRequired   int
	rsMax        int
}

func NewProgress(all int64, max, required int) *Progress {
	return &Progress{
		all:                  all,
		lastPercent:          0,
		currentSegmentFactor: 0,
		piecePercent:         make([]int32, max),
		rsRequired:           required,
		rsMax:                max,
	}
}
func (p *Progress) UpdatePiecePercent(n int, percent int32) {
	if n < 0 || n > p.rsMax {
		return
	}
	atomic.StoreInt32(&p.piecePercent[n], percent)
	//p.GetRealtimePercent()

}
func (p *Progress) SetCurrentSegment(n int64) {
	if n > p.all {
		return
	}
	p.currentSegmentFactor = float64(n) / float64(p.all)
	//for i := range p.piecePercent {
	//	atomic.StoreInt32(&p.piecePercent[i], 0)
	//}
}
func (p *Progress) CommitCurrentSegment() {
	p.lastPercent += p.currentSegmentFactor
	fmt.Println("commit 进度", p.lastPercent)
	for i := range p.piecePercent {
		atomic.StoreInt32(&p.piecePercent[i], 0)
	}

}

func (p *Progress) GetRealtimePercent() int {
	var sum int32 = 0
	for i := range p.piecePercent {
		sum += atomic.LoadInt32(&p.piecePercent[i])
	}
	sum /= int32(p.rsMax)
	fmt.Println("当前平均进度", sum)
	var percentSegment = float64(sum) / 100
	fmt.Printf("%.3f %.3f %.3f\n", p.lastPercent, p.currentSegmentFactor, percentSegment)
	var percent = int((p.lastPercent + p.currentSegmentFactor*percentSegment) * 100)
	fmt.Println("总进度 ", percent)
	return percent
}
